package com.cn.bulu.utils.Monery.weixin;

import com.alibaba.fastjson.JSON;
import com.cn.bulu.utils.Monery.weixin.util.*;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Created by mangues on 16/6/29.
 */
public class WeiXinPayUtil {
    public static String weiXinPay(String ip,String orderContent, Double price,String orderId,String url) throws Exception{
        Map<Object,Object> resInfo = new HashMap<Object, Object>();
        //接收财付通通知的URL
//        String notify_url = "http://javashuxiang.gotoip11.com/weixin_notify_url.jsp";

        //---------------生成订单号 开始------------------------
        //当前时间 yyyyMMddHHmmss
        String currTime = TenpayUtil.getCurrTime();
        //8位日期
        String strTime = currTime.substring(8, currTime.length());
        //四位随机数
        String strRandom = TenpayUtil.buildRandom(4) + "";
        //10位序列号,可以自行调整。
        String strReq = strTime + strRandom;
        //订单号，此处用时间加随机数生成，商户根据自己情况调整，只要保持全局唯一就行
        String out_trade_no = strReq;
        //---------------生成订单号 结束------------------------

//		PackageRequestHandler packageReqHandler = new PackageRequestHandler(request, response);//生成package的请求类
//		PrepayIdRequestHandler prepayReqHandler = new PrepayIdRequestHandler(request, response);//获取prepayid的请求类
//		ClientRequestHandler clientHandler = new ClientRequestHandler(request, response);//返回客户端支付参数的请求类
//		packageReqHandler.setKey(ConstantUtil.PARTNER_KEY);

//		PayReq prepayReqHandler = new PayReq();


        SortedMap<Object,Object> parameters = new TreeMap<Object, Object>();
        int retcode ;
        String retmsg = "";
        String xml_body = "";
        //获取token值

//		String token = AccessTokenRequestHandler.getAccessToken();

//		log.info("获取token------值 " + token);
//
//		if (!"".equals(token)) {
        //设置package订单参数
//			packageReqHandler.setParameter("bank_type", "WX");//银行渠道
        parameters.put("body", orderContent); //商品描述
        parameters.put("notify_url", url); //接收财付通通知的URL
        parameters.put("mch_id", ConstantUtil.mch_id); //商户号
        parameters.put("out_trade_no", orderId+"_"+out_trade_no); //商家订单号+随机数 = 支付流水号
        parameters.put("total_fee", (int)(price*100)+""); //商品金额,以分为单位
//			parameters.put("spbill_create_ip",HttpUtils.getIpAddr(request)); //订单生成的机器IP，指用户浏览器端IP
        parameters.put("spbill_create_ip",ip); //订单生成的机器IP，指用户浏览器端IP
        parameters.put("fee_type", "1"); //币种，1人民币   66
        parameters.put("trade_type", "APP"); //字符编码
//			parameters.put("device_info", "WEB"); //字符编码
//			prepayReqHandler.setParameter("input_charset", "GBK"); //字符编码

//			//获取package包
//			String packageValue = packageReqHandler.getRequestURL();
//			resInfo.put("package", packageValue);
//
//			log.info("获取package------值 " + packageValue);

        String noncestr = WXUtil.getNonceStr();
//			String timestamp = WXUtil.getTimeStamp();
//			String traceid = "";
        ////设置获取prepayid支付参数
        parameters.put("appid", ConstantUtil.APP_ID);
        parameters.put("nonce_str", noncestr);
//			prepayReqHandler.setParameter("timestamp", timestamp);
//			prepayReqHandler.setParameter("traceid", traceid);

        //生成获取预支付签名
        String sign = WXUtil.createSign(parameters);
        //增加非参与签名的额外参数
        parameters.put("sign", sign);
//			prepayReqHandler.setParameter("sign_method",
//					ConstantUtil.SIGN_METHOD);
//			String gateUrl = ConstantUtil.GATEURL + token;
//			prepayReqHandler.setGateUrl(gateUrl);

        //获取prepayId
//			String prepayid = prepayReqHandler.sendPrepay();

//			log.info("获取prepayid------值 " + prepayid);
//
//			//吐回给客户端的参数
//			if (null != prepayid && !"".equals(prepayid)) {
//				//输出参数列表
//				clientHandler.setParameter("appid", ConstantUtil.APP_ID);
////				clientHandler.setParameter("appkey", ConstantUtil.APP_KEY);
//				clientHandler.setParameter("nonce_str", noncestr);
//				//clientHandler.setParameter("package", "Sign=" + packageValue);
//				clientHandler.setParameter("package", "Sign=WXPay");
//				clientHandler.setParameter("mch_id", ConstantUtil.mch_id);
//				clientHandler.setParameter("prepayid", prepayid);
//				clientHandler.setParameter("timestamp", timestamp);
//				//生成签名
//				sign = clientHandler.createSHA1Sign();
//				clientHandler.setParameter("sign", sign);
//
//				xml_body = clientHandler.getXmlBody();
//				resInfo.put("entity", xml_body);
//				retcode = 0;
//				retmsg = "OK";
//			} else {
//				retcode = -2;
//				retmsg = "错误：获取prepayId失败";
//			}
//		} else {
//			retcode = -1;
//			retmsg = "错误：获取不到Token";
//		}
//
//		resInfo.put("retcode", retcode);
        resInfo.put("retmsg", WXUtil.getXmlBody(parameters));

        String xml = WXUtil.getXmlBody(parameters);

            byte[] bytes = HttpUtils.postXml("https://api.mch.weixin.qq.com/pay/unifiedorder",xml,"UTF-8");
            String s = new String(bytes, "UTF-8");


        SortedMap<Object, Object> finalpackage = new TreeMap<Object, Object>();
        String timestamp =  WXUtil.getTimeStamp();
        finalpackage.put("appid", ConstantUtil.APP_ID);
        finalpackage.put("timestamp", timestamp);
        finalpackage.put("noncestr", noncestr);
        finalpackage.put("partnerid", ConstantUtil.mch_id);
        finalpackage.put("package", "Sign=WXPay");
        try {
            finalpackage.put("prepayid", XMLUtil.doXMLParse(s).get("prepay_id"));
            if (XMLUtil.doXMLParse(s).get("return_code").equals("FAIL")){
                throw new Exception();
            }
        }catch (Exception e){
                throw e;
        }
        String finalsign = WXUtil.createSign(finalpackage);
        finalpackage.put("sign",finalsign);

        String strJson = JSON.toJSONString(finalpackage);
        return strJson;

    }
}
